package com.study.gateway.filter;

import com.google.common.base.Charsets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * http://127.0.0.1/order/orderFeignToMember?token=123456
 * token检测
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2020/9/23 21:35
 */
@Component
public class TokenGlobalFilter implements GlobalFilter,Ordered{
    //网关端口
    @Value("${server.port}")
    private String serverPort;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            //响应
            return respVoidMono(exchange,
                    HttpStatus.INTERNAL_SERVER_ERROR
            ,"token not is null");
        }
        //假设固定token，实际需要解析。
        if (!"123456".equals(token)) {
            return respVoidMono(exchange,
                    HttpStatus.INTERNAL_SERVER_ERROR
                    ,"token error");
        }
        //在请求头中传递数据,记录网关的端口。或者用户的ip 。
        // http://127.0.0.1/order/getServerPort?token=123456
        ServerHttpRequest request = exchange.getRequest()
                .mutate().header("serverPort", this.serverPort).build()
                .mutate().header("ip", "192.168.8.88").build()
                ;
        //责任链模式
//        return chain.filter(exchange);
        //mutate 转换
        return chain.filter(exchange.mutate().request(request).build());
    }
    //响应
    private Mono<Void> respVoidMono(ServerWebExchange exchange,
                                    HttpStatus status,
                                    String msg) {
        ServerHttpResponse response = exchange.getResponse();
        //状态码
        response.setStatusCode(status);
        DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes(Charsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        // 设置顺序
        return 0;
    }
}
